package com.fr.web;
import java.sql.Timestamp;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.fr.dao.BookDao;
import com.fr.model.Book;
import com.fr.model.Service;
import com.fr.model.User;
import net.sf.json.JSONObject;

@SuppressWarnings("serial")
public class BookServiceAction extends JsonServlet {
	private BookDao bookDao=new BookDao();
	
	@Override
	public String dealInput(Map<String, String[]> input) {
		System.out.println(input);
		Book book=getBookFromInput(input);
		bookDao.addBook(book);
		book.setId(bookDao.getId());
		return JSONObject.fromObject(book).toString();
	}

	private Book getBookFromInput(Map<String, String[]> input) {
		Book book=new Book();
		String serviceId=input.get("serviceId")[0];
		if(serviceId!=null && serviceId.matches("\\d{1,9}")) {
			Service service=new Service(Integer.parseInt(serviceId));
			book.setService(service);
			book.setPrice(bookDao.getPrice(Integer.parseInt(serviceId)));
		}
		
		book.setMessage(input.get("message")[0]);
		String nickName=input.get("nickName")[0];
		if(StringUtils.isNotBlank(nickName)) {
			User user=new User(nickName);
			book.setUser(user);
		}
		
		String date=input.get("date")[0];
		if(date!=null && 
				date.matches("\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}")) {
			Timestamp bookTime=Timestamp.valueOf(date+":00");
			book.setBookTime(bookTime);
		}
		
		return book;
	}
}
